package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import com.ruoyi.common.core.domain.model.LoginSimplenessBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.system.domain.SysUserOnline;
import eu.bitwalker.useragentutils.UserAgent;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Api(tags = "登录验证管理")
@RestController
public class SysLoginController
{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


    /**
     * 登录方法（只需要输入用户名和密码）
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("登录方法（只需要输入用户名和密码）")
    @PostMapping("/loginSimpleness")
    public AjaxResult loginSimpleness(@RequestBody LoginSimplenessBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.loginSimpleness(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


    /**
     * 用（登录IP地址+浏览器类型）获取登录token
     *
     * @return 用户信息
     */
    @ApiOperation("用（登录IP地址+浏览器类型）获取用户信息")
    @GetMapping("getLoginToken")
    public AjaxResult getLoginToken()
    {
        //1、获取当前请求的参数（登录IP地址+浏览器类型）
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        String browser = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent")).getBrowser().getName();
        String requestParam = ip+Constants.SPLIT_THREE_ANT+browser;
        logger.info("getLoginToken.requestParam|"+requestParam);
        //2、从redis中获取所有前缀为“login_tokens:”的缓存数据
        //3、将1的结果与2的结果进行循环匹配，如果找到返回loginToken，否则返回空字符串
        String loginToken = "";
        Collection<String> keys = redisCache.keys(Constants.LOGIN_TOKEN_KEY + "*");
        for (String key : keys)
        {
            LoginUser user = redisCache.getCacheObject(key);
            String requestParamRedis = user.getIpaddr()+Constants.SPLIT_THREE_ANT+user.getBrowser();
            if(requestParam.equals(requestParamRedis)){
                if(StringUtils.isNotBlank(user.getLoginToken())){
                    loginToken = user.getLoginToken();
                }
            }
        }
        AjaxResult ajax = AjaxResult.success(loginToken);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
